package com.zzxy.spring.aspect;

import com.zzxy.spring.service.IteacherService;
import com.zzxy.spring.service.impl.TeacherServiceImpl;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MyBeanFactoryCglib {
    public static IteacherService createTeacherService() {
        IteacherService teacherService = new TeacherServiceImpl();
        MyAspect aspect = new MyAspect();
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(teacherService.getClass());
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object proxy, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                aspect.before();
                Object obj = methodProxy.invokeSuper(proxy, objects);
                aspect.after();
                return obj;
            }
        });
        TeacherServiceImpl proxy = (TeacherServiceImpl) enhancer.create();
        return proxy;
    }
}

